<template>
	<el-main>
		<el-row :gutter="20">
			<el-col :span="10" :offset="6">
				<div class="detail-title">
					<span v-if="$route.query.roleId">
						修改
					</span>
					<span v-else>
						新增
					</span>
				</div>
				<el-form :model="form" :rules="rules" ref="form">
					<el-form-item label="角色名称" prop="roleName">
						<el-input v-model="form.roleName" maxlength="8" show-word-limit></el-input>
					</el-form-item>
					<el-form-item label="描述" prop="description">
						<el-input
							type="textarea" 
							rows="3" 
							maxlength="120"
							show-word-limit
							v-model="form.description">
						</el-input>
					</el-form-item>
					<el-form-item label="状态">
						<el-radio-group v-model="form.status">
							<el-radio border :label="1">启用</el-radio>
							<el-radio border :label="2">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item>
						<template v-if="!$route.query.roleId">
							<el-button type="primary" @click="createRole('form')">
								提交信息
							</el-button>
							<el-button type="warning" native-type="reset">
								重置表单
							</el-button>
						</template>
						<el-button type="primary" v-else @click="updateRole('form')">
							修改信息
						</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
	</el-main>
</template>

<script>
	import { getRoleById,createRole,updateRole } from '@/api/role.js'
	export default {
		data() {
			return {
				form: {
					status: 1
				},
				rules: {
					roleName: [
						{ required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
					]
				}
			}
		},
		mounted() {
			if (this.$route.query.roleId) {
				this.getRoleById(
					this.$route.query.roleId
				);
			}
		},
		methods: {
			// 详情信息
			getRoleById(roleId) {
				let _this = this;
				getRoleById({'roleId': roleId}).then(function(res){
					if (res.code === 200) {
						_this.form = res.data;
					}
				})
			},
			// 创建信息
			createRole(form) {
				this.$refs[form].validate((valid) => {
					let _this = this;
					if (valid) {
						createRole(_this.form).then(function(res){
							if (res.code === 200) {
								_this.$message({
									message: res.msg,
									type: 'success'
								});
								_this.$router.push('./list');
							} else {
								_this.$message.error(res.msg);
							}
						})
					}
				})
			},
			// 修改信息
			updateRole(form) {
				this.$refs[form].validate((valid) => {
					let _this = this;
					if (valid) {
						updateRole(_this.form).then(function(res){
							if (res.code === 200) {
								_this.$message({
									message: res.msg,
									type: 'success'
								});
							} else {
								_this.$message.error(res.msg);
							}
						})
					}
				})
			}
		}
	}
</script>
